package com.nintendo.gateway.filters;

import com.alibaba.nacos.shaded.com.google.gson.Gson;
import com.nintendo.exceptions.GraceException;
import com.nintendo.gateway.properties.ExcludeProperties;
import com.nintendo.gateway.properties.LimitProperties;
import com.nintendo.result.GraceJSONResult;
import com.nintendo.result.ResponseStatusEnum;
import com.nintendo.utils.IPUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static com.nintendo.base.BaseInfoProperties.USER_VISITOR_LIMIT;
import static com.nintendo.base.BaseInfoProperties.USER_VISITOR_NORMAL;

@Component
public class LimitGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private LimitProperties limitsProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String ip = IPUtil.getIP(request);
        Object visitorNormal = redisTemplate.opsForValue().get(USER_VISITOR_NORMAL + ip);
        // 查询ip是否被封禁
        Object visitorLimit = redisTemplate.opsForValue().get(USER_VISITOR_LIMIT + ip);
        if(Objects.nonNull(visitorLimit)){
            return GatewayErrorResponse( exchange);
        }
        if(Objects.isNull(visitorNormal)){
            redisTemplate.opsForValue().set(USER_VISITOR_NORMAL+ip,1,limitsProperties.getVisitorTime(), TimeUnit.SECONDS);
        }else{
            redisTemplate.opsForValue().increment(USER_VISITOR_NORMAL+ip);
        }
        Object visitorNormalObj = redisTemplate.opsForValue().get(USER_VISITOR_NORMAL + ip);
        int visitorCount = Integer.parseInt(visitorNormalObj.toString());
        if(visitorCount>limitsProperties.getCount()){
            // 封禁60s
            redisTemplate.opsForValue().set(USER_VISITOR_LIMIT+ip,"1",limitsProperties.getLimitTime(), TimeUnit.SECONDS);
            return GatewayErrorResponse( exchange);
        }
        return chain.filter(exchange);
    }

    private Mono<Void> GatewayErrorResponse(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        GraceJSONResult jsonResult =GraceJSONResult.exception(ResponseStatusEnum.SYSTEM_RESPONSE_NO_INFO);
        // 3. 设置header类型
        if (!response.getHeaders().containsKey("Content-Type")) {
            response.getHeaders().add("Content-Type",
                    MimeTypeUtils.APPLICATION_JSON_VALUE);
        }

        // 4. 修改response的状态码code为500
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);

        // 5. 转换json并且像response中写入数据
        String resultJson = new Gson().toJson(jsonResult);
        DataBuffer buffer = response
                .bufferFactory()
                .wrap(resultJson.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
